﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using LinqToExcel;
using System.Collections;
using STLGROUP.Layers.DataAccessLayers;

namespace STLGROUP.Layers.Presentations
{
    public partial class frmImportExcel : STLGROUP.Layers.Presentations.FormBase.frmBase
    {
        public bool _data = false;

        #region Constructors

        public frmImportExcel()
        {
            InitializeComponent();
        } 

        #endregion

        #region Private Methods

        #region Open

        private void Open()
        {
            OpenFileDialog open = new OpenFileDialog();
            open.Title = "Chọn file Excel";
            open.Multiselect = false;
            open.Filter = "*.xlsx|*.xlsx|*.xls|*.xls";
            DialogResult result = open.ShowDialog();

            if (result == DialogResult.OK)
            {
                txtFileName.Text = open.FileName;
            }
        } 

        #endregion

        #region GetData

        public List<T> GetData<T>()
        {
            try
            {
                var excel = new ExcelQueryFactory(txtFileName.Text);

                var q = from r in excel.WorksheetRange<T>(txtStartRange.Text, txtEndRange.Text, txtSheetName.Text)
                        select r;

                if (q.ToList().Count > 0)
                {
                    _data = true;
                    return q.ToList();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Lỗi");
            }
            _data = false;
            return null;
        }  

        #endregion

        #endregion

        #region Events

        private void btxOpen_Click(object sender, EventArgs e)
        {
            Open();
        }

        private void btxImport_Click(object sender, EventArgs e)
        {
            if (!string.IsNullOrWhiteSpace(txtFileName.Text) && !string.IsNullOrWhiteSpace(txtSheetName.Text) &&
                    !string.IsNullOrWhiteSpace(txtStartRange.Text) && !string.IsNullOrWhiteSpace(txtEndRange.Text))
            {
                _data = true;
                this.Hide();
            }
            else
            {
                _data = false;
                MessageBox.Show("Vui lòng nhập đầy đủ các thông tin", "Lỗi");
            }
        }

        private void btxReset_Click(object sender, EventArgs e)
        {
            txtFileName.Text = txtSheetName.Text = txtStartRange.Text = txtEndRange.Text = string.Empty;
        }

        private void btxExit_Click(object sender, EventArgs e)
        {
            this.Close();
        } 

        #endregion
    }
}
